﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Helper
{
    public class Utility
    {
        public static string GetConnectionString()
        {
            return "metadata=res://*/iTracker.csdl|res://*/iTracker.ssdl|res://*/iTracker.msl;provider=MySql.Data.MySqlClient;provider connection string=&quot;password=this_is_my_password;server=133.18.21.238;user id=nepal;persistsecurityinfo=True;database=subash&quot;";
        }

        public static DateTime ToDate(string date)
        {
            string dateFormat = System.Configuration.ConfigurationManager.AppSettings["dateformat"];
            DateTime dt = new DateTime();
            try
            {
                dt = DateTime.ParseExact(date, dateFormat, CultureInfo.InvariantCulture);
            }
            catch (Exception ex)
            {

                Helper.ErrorLogger.WriteLog(ex.Message, ex);
            }

            return dt;
        }

        public static string ToAreaCode(int id)
        {
            return string.Format("A{0:000}", id);
        }

        public static string PolishData(string data)
        {
            if (data.Contains("\""))
            {
                data = data.Replace("\"", "\"\"");
            }

            if (data.Contains(","))
            {
                data = String.Format("\"{0}\"", data);
            }

            if (data.Contains(System.Environment.NewLine))
            {
                data = String.Format("\"{0}\"", data);
            }
            return data.Replace(",", " ");
        }

        public static string SerializeJSon<T>(T t)
        {
            MemoryStream stream = new MemoryStream();
            DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
            DataContractJsonSerializerSettings s = new DataContractJsonSerializerSettings();
            ds.WriteObject(stream, t);
            string jsonString = Encoding.UTF8.GetString(stream.ToArray());
            stream.Close();
            return jsonString;
        }

        public static T DeserializeJSon<T>(string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(stream);
            return obj;
        }
    }
}
